import {AfterViewInit, Component, EventEmitter, OnDestroy, OnInit, Output} from '@angular/core';
import {Message} from '../../../../../../ng-tools/src/message/message';
import {AlertOptions, DynamicComponent, DynamicComponentEvent} from '../../../../../../ng-tools';
import {Subscription} from 'rxjs';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {TicketService} from '../../../../../services/api/ticket.service';
import {HttpParams} from '@angular/common/http';

@Component({
    selector: 'edit-notice',
    templateUrl: './edit-notice.component.html',
    styleUrls: ['./edit-notice.component.scss']
})
export class EditNoticeComponent implements OnInit, AfterViewInit, OnDestroy, Message, DynamicComponent {
    context: any;
    dynamic: true;
    events: DynamicComponentEvent;
    noticeForm: FormGroup;
    subscriptions: Subscription;
    currentNotice;
    alertOptions: AlertOptions = {
        data: null,
        position: 'center'
    };
    @Output() success = new EventEmitter();
    set data(value: any) {
        this.currentNotice = value;
    }

    constructor(private formBuilder: FormBuilder,
                private ticketService: TicketService) {
        this.noticeForm = this.formBuilder.group({
            val: ['', Validators.required],
        });
    }
    trigger(eventName: string, ...args) {
        this[eventName].emit(...args);
        if (eventName in this.events) {
            this.events[eventName](...args);
        }
    }
    ngOnInit() {
        this.noticeForm.patchValue({'val': this.currentNotice});
    }
    save() {
        if (this.noticeForm.valid) {
            this.ticketService.post(this.ticketService.urls.updatePlatAnnoucement, this.noticeForm.value, {
              observe: 'response',
              params: new HttpParams().append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
                this.trigger('success', this.noticeForm.value);
            });
        }
    }
    ngAfterViewInit(): void {
    }

    ngOnDestroy(): void {
    }

}
